﻿using Microsoft.Extensions.DependencyInjection;
using Hangfire;
using RxxAdmin.Common;
using Hangfire.SqlServer;
using Microsoft.AspNetCore.Builder;
using Hangfire.Dashboard.BasicAuthorization;
using Hangfire.Redis.StackExchange;

namespace RxxAdmin.Extensions;
/// <summary>
/// 任务调度  启动服务
/// </summary>
public static class HangfireJobSetup
{
    public static void AddHangfireJobSetup(this IServiceCollection services) {
        if (services == null) throw new ArgumentNullException(nameof(services));

        if (AppSettings.HangfireSetting.Enabled)
        {
            //添加hangfire服务
            services.AddHangfire(configuration => configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) // 设置数据兼容性级别为 1.7 版本
                .UseSimpleAssemblyNameTypeSerializer() // 使用简单的程序集名称类型序列化器
                .UseRecommendedSerializerSettings() // 使用推荐的序列化器设置
                //.UseSqlServerStorage(AppSettings.HangfireSetting.SqlServer, new SqlServerStorageOptions
                //{
                //    //持久化
                //    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), // 批处理作业的最大超时时间为 5 分钟
                //    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), // 作业的可见性超时时间为 5 分钟
                //    QueuePollInterval = TimeSpan.FromSeconds(5), // 检查作业队列的间隔时间为 5 秒
                //    JobExpirationCheckInterval = TimeSpan.FromHours(1),//- 作业到期检查间隔（管理过期记录）。默认值为1小时。
                //    CountersAggregateInterval = TimeSpan.FromMinutes(5),//- 聚合计数器的间隔。默认为5分钟。
                //                                                        //DashboardJobListLimit=5000,//- 仪表板作业列表限制。默认值为50000。
                //    TransactionTimeout = TimeSpan.FromMinutes(1),//- 交易超时。默认为1分钟。
                //    UseRecommendedIsolationLevel = true, // 使用推荐的事务隔离级别
                //    DisableGlobalLocks = true // 禁用全局锁定机制
                //})
                .UseRedisStorage(AppSettings.HangfireSetting.Redis, new RedisStorageOptions
                {
                    FetchTimeout = TimeSpan.FromMinutes(5),
                    //活动服务器超时时间
                    InvisibilityTimeout = TimeSpan.FromMinutes(30),
                    Db = Convert.ToInt32(AppSettings.HangfireSetting.Db),
                    //任务过期检查频率
                    ExpiryCheckInterval = TimeSpan.FromMinutes(5),
                    DeletedListSize = 10000,
                    SucceededListSize = 10000
                })
            );
            services.AddHangfireServer(); // 添加 Hangfire 服务器
        }
    }

    public static void UseHangfireJobMiddle(this IApplicationBuilder app)
    {
        if (app == null) throw new ArgumentNullException(nameof(app));

        if (AppSettings.HangfireSetting.Enabled)
        {
            //启用仪表盘
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] {
                new BasicAuthAuthorizationFilter(
                    new BasicAuthAuthorizationFilterOptions
                    {
                        SslRedirect = false,
                        RequireSsl = false,
                        LoginCaseSensitive = false,
                        Users = new[]
                        {
                            new BasicAuthAuthorizationUser
                            {
                                Login = AppSettings.HangfireSetting.Login, //可视化的登陆账号
                                PasswordClear = AppSettings.HangfireSetting.Password //可视化的密码
                            }
                        }
                    }
                )
            }
            });

            HangfireService.Service();
        }
    }
}
